package com.shenzhen.horselive.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.flqy.baselibrary.BuildConfig;
import com.flqy.baselibrary.utils.L;
import com.flqy.baselibrary.utils.ViewUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.common.Events;
import com.shenzhen.horselive.common.SafeConsumer;
import com.shenzhen.horselive.common.utils.Permissions;
import com.shenzhen.horselive.common.utils.Utils;
import com.shenzhen.horselive.presenter.BasePresenter;
import com.shenzhen.horselive.presenter.BaseView;
import com.shenzhen.horselive.presenter.PresenterFactory;
import com.shenzhen.horselive.widget.LoadingDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.NumberFormat;

import me.jessyan.autosize.internal.CustomAdapt;

import static androidx.lifecycle.Lifecycle.State.CREATED;

public class BaseActivity<T extends BasePresenter> extends AppCompatActivity implements BaseView, LoadingDialog.OnBackListener {
    protected T mPresenter;//Presenter对象
    private LoadingDialog loadingDialog;
    //是否需要统计该页面
    private static boolean needTrack = !BuildConfig.DEBUG;
    protected InputMethodManager inputMethodManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        }
        super.onCreate(savedInstanceState);
        ActivityCollector.addActivity(this, getClass());
        EventBus.getDefault().register(this);
        loadingDialog = new LoadingDialog(this);
        mPresenter = createPresenter();//创建Presenter
        if (mPresenter != null) {
            mPresenter.onAttach(this);
        }
//        setTranslucentStatus();
        loadingDialog.setOnBackListener(this);

        Permissions.of(this).request(getString(R.string.get_phone_state_error), Manifest.permission.READ_PHONE_STATE).subscribe(new SafeConsumer<Boolean>() {
            @Override
            public void accept(Boolean granted) {
            }
        });

        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

    }




    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.onDetach();
        }
        ActivityCollector.removeActivity(this);
        EventBus.getDefault().unregister(this);
    }


    /**
     * @param cls 目标activity
     *            跳转并finish当前activity
     */
    public void skipActivity(Class<?> cls) {
        skipActivity(cls, null);
    }

    /**
     * @param cls
     * @param extras
     */
    public void skipActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        if (extras != null) {
            intent.putExtras(extras);
        }
        intent.setClass(this, cls);
        startActivity(intent);
        finish();
    }

    public void showActivityForResult(Class<?> cls, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        super.startActivityForResult(intent, requestCode);
        ViewUtils.anima(ViewUtils.RIGHT_IN, this);
    }

    public void showActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtras(bundle);
        super.startActivityForResult(intent, requestCode);
        ViewUtils.anima(ViewUtils.RIGHT_IN, this);
    }

    public void showActivity(Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        super.startActivity(intent);
        ViewUtils.anima(ViewUtils.RIGHT_IN, this);
    }

    public void showActivity(Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.putExtras(extras);
        super.startActivity(intent);
        ViewUtils.anima(ViewUtils.RIGHT_IN, this);
    }

    public void showNewTaskActivity(Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        super.startActivity(intent);
    }

    @Override
    public void finish() {
        super.finish();
        applyCloseTransition();
    }

    protected void applyCloseTransition() {
        ViewUtils.anima(ViewUtils.NONE, this);
    }


    public Context getContext() {
        return this;
    }

    protected void setTranslucentStatus() {
        ImmersionBar.with(this).statusBarDarkFont(true).init();
    }


    @Override
    public void showLoading() {
        if (!loadingDialog.isShowing()) {
            loadingDialog.show();
        }
    }

    @Override
    public void hideLoading() {
        if (loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    protected PresenterFactory getPresenterFactory() {
        return PresenterFactory.DEFAULT;
    }

    private T createPresenter() {
        return getPresenterFactory().create(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotifyClose(Events.CloseEvent closeEvent) {
        if (closeEvent.eventType.equals(Events.CloseEvent.FINISH_ALL)) {
            if (closeEvent.ignoreClass != null) {
                if (Utils.contain(closeEvent.ignoreClass, getClass().getName())) {
                    L.i("CloseEvent", "not finish:" + getClass().getName());
                    return;
                }
            }
            L.i("CloseEvent", "finish:" + getClass().getName());
            finish();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void showError(Throwable ex) {
        Utils.showError(this, ex);

    }

    @Override
    public boolean isActive() {
        return getLifecycle().getCurrentState().isAtLeast(CREATED);
    }

    public T getPresenter() {
        return mPresenter;
    }

    @Override
    public void onLoadingBack() {

    }


    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public  void showToast(String msg)
    {
        Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }

    public  void showLongToast(String msg)
    {
        Toast.makeText(this,msg,Toast.LENGTH_LONG).show();
    }


    //全屏
    public void  tranFullImmbar()
    {
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .init();
    }



    //格式化后台给的傻逼数据，操你妈的后台傻逼
    protected   String  formatFuckingNumber(String  number)
    {
        if ("0E-10".equals(number)|| TextUtils.isEmpty(number))
        {
            return "0";
        }
        if (number!=null)
        {
        NumberFormat  format =  NumberFormat.getInstance();
        format.setMaximumFractionDigits(10);
        format.setGroupingUsed(false);
        return format.format(Double.parseDouble(number));
        }
        else
        {
            return "0";
        }
    }



}
